#coding: utf-8
import random
import time
import threading
import Queue

from math import sin,cos,radians

random.seed(time.time())

stop=False


class Ball(object):
    def __init__ (self):
        self.weight=random.randrange(1,10)


class Wind(object):
    def __init__ (self):
        self.speed=random.randrange(-5,5)

class Throw(object):
    def __init__ (self):
        self.force=random.randrange(0,150)
        self.angle=random.randrange(10,90)


class Player(threading.Thread):
    def __init__ (self,name,q_state):
        threading.Thread.__init__(self)
        self.name=name
        self.total_score=0
        self.q_state=q_state
    def run (self):
        while not stop:
            now=time.time()
            self.q_state.put((self,Throw(),Ball(),Wind(),now))
            time.sleep(0.1)#龟速,故意降低产生的速度

class Handle(threading.Thread):
    def __init__ (self,end_time,q_state):
        threading.Thread.__init__(self)
        self.end_time=end_time
        self.q_state=q_state
    def run (self):
        while True:
            try:
                player,throw,ball,wind,now=self.q_state.get(timeout=0.5)
            except Queue.Empty:
                if stop:
                    break
                else:
                    continue
            print '%s throw a %dm ball and wind is %d '%(player.name,ball.weight,wind.speed),
            v=throw.force/ball.weight
            if v*cos(radians(throw.angle))+wind.speed<=0:#抛到自己后面去了
                print 'score is 0'
            else:
                t=2*v*sin(radians(throw.angle))/10
                if now+t>self.end_time:#游戏停止时，球还在空中
                    print 'score is 0'
                else:
                    s=v*v*sin(2*radians(throw.angle))/float(10)
                    if s>5:#抛的太远了
                        print 'score is 0'
                    else:
                        score=int(10-(5-s)*2)
                        print 'score is %d'%score
                        player.total_score+=score

class Game(object):
    def __init__ (self,timeout=2,user_num=2):
        self.user_num=user_num
        self.timeout=timeout
        self.q_state=Queue.Queue()
    def start (self):
        start_time=time.time()
        player_list=[]
        handle=Handle(self.timeout+start_time,self.q_state)
        handle.setDaemon(True)
        handle.start()
        for i in xrange(1,self.user_num+1):
            player=Player("player%d"%i,self.q_state)
            player.start()
            player_list.append(player)
        t = threading.Timer(self.timeout, self._stop)
        t.start()
        handle.join()
        for player in player_list:
            print "%s's total socre is %d"%(player.name,player.total_score)

    def _stop (self):
        global stop
        stop=True
        #print 'I am stop'
game=Game(timeout=60)
game.start()